<?php
require_once 'Zend/Acl.php';

class Etian_Controllers_Plugins_AclAndAuth 
		extends Zend_Controller_Plugin_Abstract {
			
    private $_auth;
    private $_acl;

  
    public function __construct($auth)
    {
        $this->_auth = $auth;
        $this->_acl = new Zend_Acl();
        $this->initAcl();    
        
    }

    protected function initAcl() {
    	
 		require_once 'Zend/Acl/Resource.php';
		$this->_acl->add(new Zend_Acl_Resource('admarea'));
		$this->_acl->add(new Zend_Acl_Resource('error'));
		$this->_acl->add(new Zend_Acl_Resource('index'));		
		$this->_acl->add(new Zend_Acl_Resource('rulesofengagement'));
		$this->_acl->add(new Zend_Acl_Resource('dailythought'));
		$this->_acl->add(new Zend_Acl_Resource('yournilink'));
		$this->_acl->add(new Zend_Acl_Resource('somestats'));
		
		require_once 'Zend/Acl/Role.php';
        $this->_acl->addRole(new Zend_Acl_Role('guest')); 
        $this->_acl->addRole(new Zend_Acl_Role('admin'));

        // Guest may only view content
		$this->_acl->deny('guest', 'admarea');		
		$this->_acl->allow('guest', 'admarea', 'index');
		$this->_acl->allow('guest', 'admarea', 'login');
		$this->_acl->allow('guest', 'error', 'error'); 
        $this->_acl->allow('guest', 'index');        
        $this->_acl->allow('guest', 'rulesofengagement');
        $this->_acl->allow('guest', 'dailythought');
        $this->_acl->allow('guest', 'yournilink');
        $this->_acl->allow('guest', 'somestats');        
        $this->_acl->allow('admin'); // unrestricted access
    	
    }
      
	public function preDispatch($request)
	{
        if ($this->_auth->hasIdentity()) { 
        	$role = 'admin';   	$request->setParam('role', 'admin'); 
        } else {      	$role = 'guest';   $request->setParam('role', 'guest');     }
       
    	$controller = $request->getControllerName();
    	$action = $request->getActionName();
    	$module = $request->getModuleName();
		$resource = $controller;
		  		
	    if (!$this->_acl->has($resource)) {$resource = null;  	}
		
	    //If permitted - even if doesn't exist! - carries on because will
		//later cause eventually an exception and get caught by the errorhandler!
        if (!$this->_acl->isAllowed($role, $resource, $action)) {
        	//echo 'test';
        	//not allowed urls section
        	if ($resource=='admarea') {
        		//redirect to the login page at each admarea acces attempt  
		        $action = 'index';         		            
	            $request->setActionName($action);
        	}        
        } else { 
        	//Redirect to the main page instead of the login page if already admin!        
        	if ($role=='admin'&&$controller=='admarea'&&$action=='index') {
        		$action = 'clientselectform';         		            
	            $request->setActionName($action);
        	}
        }
        
        
       	//redirect section

		
	}
	
}

?>